import uuid

from django import http
from django.template import loader
from django import forms
from django.conf import settings
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User, Group

from EE.logic import user as user_logic
from EE.logic import user_profile as user_profile_logic
from EE.logic import game_state as game_state_logic
from EE.models import Game
from EE.views import handler


class UserTeacherForm(forms.Form):
  """TODO: Docstring """

  login = forms.CharField(max_length=30)
  firstname = forms.CharField(max_length=30)
  lastname = forms.CharField(max_length=30)
  password = forms.CharField(max_length=10, widget=forms.widgets.PasswordInput())
  group = forms.ModelChoiceField(Group.objects.all().filter(name='Leraar'), empty_label=None)
  game = forms.ModelMultipleChoiceField(Game.objects.all(), required=False)

class UserGroupForm(forms.Form):
  login = forms.CharField(max_length=30)
  firstname = forms.CharField(max_length=30)
  password = forms.CharField(max_length=10, widget=forms.widgets.PasswordInput())
  group = forms.ModelChoiceField(Group.objects.all().filter(name='Groep'), empty_label=None)
  game = forms.ModelMultipleChoiceField(Game.objects.all(), required=False)

class ChangePassForm(forms.Form):
  """TODO: Docstring"""

  password = forms.CharField(max_length=10, widget=forms.widgets.PasswordInput())
  password_again = forms.CharField(max_length=10, widget=forms.widgets.PasswordInput())

  def clean(self):
    # rely on 'required' check to kick in
    if not self.cleaned_data.get('password'):
      return self.cleaned_data

    # rely on 'required' check to kick in
    if not self.cleaned_data.get('password_again'):
      return self.cleaned_data

    if self.cleaned_data['password'] == self.cleaned_data['password_again']:
      return self.cleaned_data

    del self.cleaned_data['password']
    del self.cleaned_data['password_again']

    raise forms.ValidationError("The entered passwords are not the same")


class CreateUser(handler.Handler):
  """Handler to handle user requests"""
  
  def getPostForm(self):
    if user_profile_logic.getType(self.user) == 'Beheerder':		
		return UserTeacherForm(self.POST)
    else:
		return UserGroupForm(self.POST)
  
  def getGetForm(self):
    if user_profile_logic.getType(self.user) == 'Beheerder':		
		return UserTeacherForm()
    else:
		return UserGroupForm()

  def post(self):
    login = self.cleaned_data['login']
    firstname = self.cleaned_data['firstname']
    type = self.cleaned_data['group']
    try:
      lastname = self.cleaned_data['lastname']
    except KeyError:
      lastname = ''
    password = self.cleaned_data['password']
    
    games = self.cleaned_data.get('game', [])
	
    user = user_logic.handle_add_user(login, firstname, lastname, password, type, games)
	
    if user_profile_logic.getType(user) == 'Groep':
       game_state = game_state_logic.createNew(user)

    return http.HttpResponseRedirect('./home')

  def get(self):
    context = self.getContext()
    content = loader.render_to_string('user/new.html', dictionary=context)
    return http.HttpResponse(content)


class Home(handler.Handler):
  """Handler to handle the user views"""
  
  def post(self):
    return http.HttpResponseRedirect('../home')
    
  def get(self):
    context = self.getContext()
    users = User.objects.all()
	
    result = []
    if user_profile_logic.getType(self.user) == 'Beheerder':
       for u in users:
	      if user_profile_logic.getType(u) == 'Leraar':
	         result.append((u, user_profile_logic.getProfile(u)))
    elif user_profile_logic.getType(self.user) == 'Leraar':
	   for u in users:
	      if user_profile_logic.getType(u) == 'Groep':
		     result.append((u, user_profile_logic.getProfile(u)))
	
	   

    #result = [(i, user_profile_logic.getProfile(i)) for i in users]

    context['users'] = result
	
    #print result

    content = loader.render_to_string('user/home.html', dictionary=context)
    return http.HttpResponse(content)


class PassChange(handler.Handler):
  """Handler to handle the change password requests"""

  def authenticated_disabled(self):
    context = self.getUserAuthenticationContext()
    user = self.user
    return context['is_beheerder']

  def getGetForm(self):
    return ChangePassForm()

  def getPostForm(self):
    return ChangePassForm(self.POST)

  def post(self):
    user_id = self.kwargs['user_id']
    password = self.cleaned_data['password']

    user_logic.handle_pass_change(user_id, password)
    return http.HttpResponseRedirect('../home')

  def get(self):
    context = self.getContext()
    content = loader.render_to_string('user/change.html', dictionary=context)
    return http.HttpResponse(content)